package org.linlinjava.litemall.admin.schedule;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.admin.task.ActivityExpiredTask;
import org.linlinjava.litemall.admin.task.ActivityStartTask;
import org.linlinjava.litemall.core.task.TaskService;
import org.linlinjava.litemall.core.util.BeanUtil;
import org.linlinjava.litemall.db.domain.LitemallActivity;
import org.linlinjava.litemall.db.service.LitemallActivityService;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling
public class ActivityStateScheduleTask {

    private final Log logger = LogFactory.getLog(ActivityStateScheduleTask.class);

    //@Scheduled(cron = "0 0/10 * * * ?")
    //或直接指定时间间隔，例如：5秒
    //@Scheduled(fixedRate=5000)
    private void configureTasks() {
        logger.info("---ActivityStateScheduleTask start---");

        LitemallActivityService activityService = BeanUtil.getBean(LitemallActivityService.class);
        TaskService taskService = BeanUtil.getBean(TaskService.class);

        List<LitemallActivity> activityList = activityService.queryByState(LitemallActivity.StateEnum.shallStatistics());

        for (LitemallActivity activity : activityList) {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime expire = activity.getEndTime();

            // 到期自动下线
            if (expire.isBefore(now)) {
                // 已经过期，马上加入队列执行
                taskService.addTask(new ActivityExpiredTask(activity.getId(), 0L));
            } else {
                // 还没过期，设置延迟执行时间 则加入延迟队列
                long delay = ChronoUnit.MILLIS.between(now, expire);
                taskService.addTask(new ActivityExpiredTask(activity.getId(), delay));
            }

            // 到期自动开始
            LocalDateTime startTime = activity.getStartTime();
            if (startTime.isBefore(now)) {
                // 已经到开始时间，马上加入队列执行
                taskService.addTask(new ActivityStartTask(activity.getId(), 0L));
            } else {
                // 还没到开始时间，设置延迟执行时间 加入延迟队列
                long delay = ChronoUnit.MILLIS.between(now, startTime);
                taskService.addTask(new ActivityStartTask(activity.getId(), delay));
            }
        }


        logger.info("---ActivityStateScheduleTask end---");
    }
}
